package tom.change.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.TypeVariable;

/**
 * 开始通过反射获取注解内容
 * @author xinhua
 *
 */
public class Junit
{

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException
    {
        Class<?> userClass = Class.forName("tom.change.annotation.User");
        //实例化
        Object userObject = userClass.newInstance();
        //1--获取最外层的就是类的注解  TypeAnno
        System.out.println(".......................类注解.......................");
        TypeAnno typeAnno= userClass.getAnnotation(TypeAnno.class);
        System.out.println(typeAnno.desc());
        //2--获取字段注解 首先获取通过反射获取类中的属性字段
        System.out.println(".......................字段注解.......................");
        Field[] fields = userClass.getDeclaredFields();
        for (Field field : fields)
        {
            FieldAnno fieldAnno = field.getAnnotation(FieldAnno.class);
            System.out.println(fieldAnno.desc());
        }
        //3-- 方法的注解
        System.out.println(".......................方法注解.......................");
        Method method = userClass.getMethod("doHomeWork", String.class,String.class);
        MethodAnno methodAnno = method.getAnnotation(MethodAnno.class);
        System.out.println(methodAnno.time()+"@@@"+methodAnno.sex());
        
        //4-- 参数的注解  动态代理方式实现参数
        System.out.println(".......................参数注解.......................");
        UserImp userImp=getMethodParameter(UserImp.class);
        userImp.DoHouseWork("张新华", "--》扫地");
        
        //5--局部变量注解 
        System.out.println(".......................局部变量注解.......................");
        //赞未获得到
    }
    
    public static<T> T getMethodParameter(Class<T> target){
        return (T)Proxy.newProxyInstance(target.getClassLoader(), new Class<?>[]{target}, new InvocationHandler()
        {
            
            @Override
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable
            {
                Annotation[][] parameterAnnotations = method.getParameterAnnotations();
                for (int i=0;i<parameterAnnotations.length;i++)
                {
                    Annotation[] annotations=parameterAnnotations[i];
                    StuInfo stuInfo =(StuInfo) annotations[0];
                    System.out.println(stuInfo.value()+"@@@"+args[i]);
                }
                
                return null;
            }
        });
    }
}
